import React, { useState, useEffect } from 'react';
import { Tabs } from 'antd-mobile';
import Lists from './components/Lists/index';
import CommonEmuns from '@/enums';
import { isEmpty } from 'project-libs';

import './index.less';
import { useObserverHook } from '@/hooks';

import { Http } from '@/utils';
import CommonEnums from '@/enums';

const order: React.FC<any> = (props: any) => {
  const tabs = [
    {
      title: '未支付',
      sub: 0,
    },
    {
      title: '已支付',
      sub: 1,
    },
  ];
  const [page, setPage] = useState(CommonEmuns.PAGE);
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [type, setType] = useState(0);

  const invokeHttp = async (pageNum: any) => {
    return await Http({
      url: '/order/lists',
      body: {
        ...page,
        pageNum,
        type,
      },
    });
  };
  const fetchOrder = async (pageNum: any) => {
    const result: any = await invokeHttp(pageNum);
    if (!isEmpty(result) && result.length === page.pageSize) {
      setOrders(result);
      setLoading(true);
    } else {
      setLoading(false);
    }
  };

  const handelChange = (v: any) => {
    setType(v.sub);
    setPage(CommonEnums.PAGE);
    setOrders([]);
    setLoading(true);
  };

  useEffect(() => {
    fetchOrder(1);
  }, [type]);

  useObserverHook(
    '#' + CommonEnums.LOADING_ID,
    async (entries) => {
      if (entries[0].isIntersecting) {
        const result: any = await invokeHttp(page.pageNum + 1);
        if (!isEmpty(result) && result.length === page.pageSize) {
          setOrders([...result, ...orders]);
          setPage({
            ...page,
            pageNum: page.pageNum + 1,
          });
          setLoading(true);
        } else {
          setLoading(false);
        }
      }
    },
    null,
  );
  // const [orders,showLoading] = useHttpHook({ url: '/order/lists', body: { ...CommonEmuns.PAGE  } })
  return (
    <div className="order-page">
      <Tabs tabs={tabs} onChange={handelChange}>
        <div className="tab">
          <Lists showLoading={loading} orders={orders} type={0} />
        </div>
        <div className="tab">
          <Lists showLoading={loading} orders={orders} type={1} />
        </div>
      </Tabs>
    </div>
  );
};

export default order;
